package web

import (
	"net"
	"net/http"
)

// HandleFunc 路由处理方法
type HandleFunc func(ctx *Context)

var _ Server = &httpServer{}

// Server 服务接口
type Server interface {
	// Handler 组合原生http处理方法
	http.Handler
	// Start 服务启动方法
	Start(addr string) error
	// AddRoute 添加路由方法
	AddRoute(method, path string, handler HandleFunc)
}

type httpServer struct {
	router
}

func NewHttpServer() *httpServer {
	return &httpServer{
		router: newRouter(),
	}
}

// server 路由业务逻辑处理方法
func (h *httpServer) server(ctx *Context) {
	route, ok := h.findRoute(ctx.Req.Method, ctx.Req.URL.Path)
	if !ok || route.n.handler == nil {
		ctx.Resp.WriteHeader(http.StatusNotFound)
		ctx.Resp.Write([]byte("PAGE NOT FOUND"))
		return
	}
	ctx.PathParams = route.pathParam
	route.n.handler(ctx)
}

// ServerHttp 初始化http服务句柄
func (h *httpServer) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	ctx := &Context{
		Req:        request,
		Resp:       writer,
		PathParams: make(map[string]string),
	}
	h.server(ctx)
}

// Start 启动http服务
func (h *httpServer) Start(addr string) error {
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	// 这里有两个参数，分别的决定监听什么服务，以及监听服务处理的对象
	return http.Serve(listener, h)
}

func (h *httpServer) AddRoute(method, path string, handler HandleFunc) {
	h.router.addRoute(method, path, handler)
}
